const path = require('path');
// const resolve = dir => {
//     return path.join(__dirname, dir);
// };
// const GenerateAssetPlugin = require('generate-asset-webpack-plugin')
const webpack = require('webpack');
// gzip压缩
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
// const UglifyJSPlugin = require('uglifyjs-webpack-plugin') // 压缩js
// 配置自动生成
/* eslint-disable no-new */
// let createServerConfig = function(compilation) {
//     var parseEnv = Object.assign({
//         _hash: compilation.hash
//     }, { VUE_APP_API: process.env.VUE_APP_API })
//     Object.keys(parseEnv).forEach(function(key) {
//         parseEnv[key] = parseEnv[key].replace(/"/g, '')
//     })
//     return JSON.stringify(parseEnv, null, 2)
// }
const cdn = {
    externals: {
        vue: 'Vue',
        vuex: 'Vuex',
        // 'vue-router': 'VueRouter',
        ELEMENT: 'ELEMENT',
        // 'vue-i18n': 'VueI18n',
        // axios: 'axios',
        // echarts: 'echarts',
        // jQuery: 'jquery',
        AMap: 'AMap',
        subway: 'subway'
    },
    js: [
        'https://unpkg.com/vue@2.6.12/dist/vue.min.js',
        'https://unpkg.com/vuex@3.5.1/dist/vuex.min.js',
        // 'https://unpkg.com/vue-router@3.4.7/dist/vue-router.js',
        // 'https://unpkg.com/vue-i18n@8.15.2/dist/vue-i18n.js',
        'https://unpkg.com/element-ui@2.13.2/lib/index.js',
        // 'https://unpkg.com/axios@0.18.0/dist/axios.min.js',
        // '//unpkg.com/echarts@4.9.0/dist/echarts.js',
        // '//unpkg.com/echarts-wordcloud@1.1.3/dist/echarts-wordcloud.js',
        // 'https://unpkg.com/jquery@3.4.1/dist/jquery.min.js',
        'https://webapi.amap.com/maps?v=1.4.15&key=527114d7af3d4ff11645f7d53c8ac20f&plugin=AMap.MouseTool,AMap.CircleEditor,AMap.RectangleEditor,AMap.PolyEditor,AMap.Geocoder,AMap.DistrictSearch'
    ]
};
// 是否为生产环境
const isProduction = process.env.NODE_ENV !== 'development';
// 本地环境是否需要使用cdn
const devNeedCdn = true;
module.exports = {
    publicPath: '/',
    productionSourceMap: false,
    chainWebpack: (config) => {
        // config.module
        //     .rule('images')
        //     .test(/\.(png|jpe?g|gif)(\?.*)?$/)
        //     .use('image-webpack-loader')
        //     .loader('image-webpack-loader')
        //     .options({
        //         bypassOnDebug: true
        //     })
        // 注入cdn start
        config.plugin('html').tap((args) => {
            // 生产环境或本地需要cdn时，才注入cdn
            if (isProduction || devNeedCdn) args[0].cdn = cdn;
            return args;
        });
        config.resolve.symlinks(true);
    },
    configureWebpack: (config) => {
        const plugins = [
            // new GenerateAssetPlugin({
            //     filename: './public/serverConfig.json',
            //     fn: (compilation, cb) => {
            //         cb(null, createServerConfig(compilation))
            //     },
            //     extraFiles: []
            // }),
            new webpack.ProvidePlugin({
                $: 'jquery',
                jQuery: 'jquery',
                'windows.jQuery': 'jquery',
                'window.$': 'jquery'
            })
        ];
        if (!isProduction) {
            // 开发环境配置
            // config.devtool = 'source-map'
        } else {
            // 生产环境  取消console打印
            config.optimization.minimizer[0].options.terserOptions.compress.warnings = false;
            config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true;
            plugins.push(
                // gzip压缩 gzip压缩的配置
                new CompressionWebpackPlugin({
                    algorithm: 'gzip',
                    test: /\.(html|js|css)$/,
                    threshold: 520, //520字节以上才开启压缩
                    minRatio: 0.8
                })
                // new webpack.optimize.LimitChunkCountPlugin({
                //     maxChunks: 20,
                //     minChunkSize: 100
                // }),
                // new BundleAnalyzerPlugin()
            );
            config.optimization.splitChunks = {
                chunks: 'all', //表示哪些代码需要优化，有三个可选值：initial(初始模块)、async(按需加载模块)、all(全部模块)，默认async
                maxInitialRequests: Infinity, //按需加载时最大的并行请求数，默认5
                minSize: 30000, //依赖包超过30000bit将被单独打包
                // maxSize: 0,
                // minChunks: 1,
                // maxAsyncRequests: 6,
                automaticNameDelimiter: '~',
                cacheGroups: {
                    // vendors: {
                    //     name: `app-chunk-vendors`,
                    //     test: /[\\/]node_modules[\\/]/,
                    //     priority: -10,
                    //     maxSize: 102400,
                    //     chunks: 'all' //'initial'
                    // },
                    zrDrawHtml: {
                        chunks: 'all',
                        name: `zr-draw-html`,
                        test: /[\\/]zr-draw-html[\\/]/,
                        priority: 0
                    },
                    // common: {
                    //     name: `chunk-common`,
                    //     minChunks: 2,
                    //     priority: -20,
                    //     chunks: 'initial',
                    //     reuseExistingChunk: true
                    // },
                    VideoPlayer: {
                        chunks: 'all',
                        name: `vue-video-player`,
                        test: /[\\/]vue-video-player[\\/]/,
                        priority: 0
                    },
                    quillEditor: {
                        chunks: 'all',
                        name: `vue-quill-editor`,
                        test: /[\\/]vue-quill-editor[\\/]/,
                        priority: 0
                    },
                    VueCron: {
                        chunks: 'all',
                        name: `vue-cron`,
                        test: /[\\/]vue-cron[\\/]/,
                        priority: 0
                    },
                    xlsx: {
                        chunks: 'all',
                        name: `xlsx`,
                        test: /[\\/]xlsx[\\/]/,
                        priority: 0
                    },
                    html2canvas: {
                        chunks: 'all',
                        name: `html2canvas`,
                        test: /[\\/]html2canvas[\\/]/,
                        priority: 0
                    },
                    brace: {
                        chunks: 'all',
                        name: `brace`,
                        test: /[\\/]brace[\\/]/,
                        priority: 0
                    },
                    dataBasicePlatform: {
                        chunks: 'all',
                        name: `dataBasicePlatform`,
                        test: /[\\/]dataBasicePlatform[\\/]/,
                        priority: 0
                    }
                }
            };
        }
        // 用cdn方式引入，则构建时要忽略相关资源
        if (isProduction || devNeedCdn) config.externals = cdn.externals;
        config.plugins = config.plugins.concat(plugins);
    },
    pluginOptions: {
        // 第三方插件配置
        'style-resources-loader': {
            preProcessor: 'less',
            patterns: [path.resolve(__dirname, './src/assets/css/variables.less')] // less所在文件路径
        }
    },
    devServer: {
        // 处理host不识别
        disableHostCheck: false,
        // 配置自动启动浏览器
        open: true,
        overlay: {
            warnings: false,
            errors: true
        },
        proxy: {
            '/': {
                ws: false, // proxy websockets
                // target: process.env.VUE_APP_API,
                target: "",
                changeOrigin: true,
                pathRewrite: {
                    '^/': '' //需要rewrite重写的,
                },
                bypass: function (req, res, proxyOptions) {
                    //history模式下本地启动跳过服务器
                    if (req.headers.accept.indexOf('html') !== -1) {
                        console.log('Skipping proxy for browser request.');
                        return '/index.html';
                    }
                }
            }
        }
    }
};
